package com.greenhouse.controller;

import com.greenhouse.config.Request;
import com.greenhouse.model.CropInfo;
import com.greenhouse.service.CropInfoService;
import com.greenhouse.utily.SessionUtils;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@RequestMapping("/cropInfo")
public class CropInfoController {
    @Autowired
    private CropInfoService cropInfoService;
    //管理员添加作物，删除作物，修改作物，查看作物信息
    @RequestMapping("/add")
    public Request<CropInfo> addCrop(HttpServletRequest request, CropInfo cropInfo) {
        if (!SessionUtils.isAdminUser(request)) {
            return Request.error("权限不足", null);
        }
        cropInfo.setUserId(SessionUtils.getSessionUser(request).getId());
        if (cropInfoService.addCrop(cropInfo)){
            return Request.success("添加作物成功", cropInfo);
        }
        return Request.error("添加作物失败", null);
    }
    @RequestMapping("/show")
    public Request<List<CropInfo>> showCrop(HttpServletRequest request){
        if (!SessionUtils.isUserLoggedIn(request)){
            return Request.error("用户未登录", null);
        }
        List<CropInfo> list = cropInfoService.showCrop();
        return Request.success("查询成功", list);
    }
    @RequestMapping("/delete")
    public Request<Boolean> deleteCrop(HttpServletRequest request, Integer cropId){
        if (!SessionUtils.isAdminUser(request)){
            return Request.error("权限不足", null);
        }
        if (cropInfoService.deleteCrop(cropId)){
            return Request.success("删除成功", true);
        }
        return Request.error("删除失败", false);

    }
    @RequestMapping("/update")
    public Request<CropInfo> updateCrop(HttpServletRequest request, CropInfo cropInfo){
        if (!SessionUtils.isAdminUser(request)){
            return Request.error("权限不足", null);
        }
        return Request.success("修改成功", cropInfoService.updateCrop(cropInfo));
    }
}
